import sys
import cv2
import matplotlib.pyplot as plt
from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtCore import Qt
from custom.stackedWidget import StackedWidget
from custom.treeView import FileSystemTreeView
from custom.listWidgets import FuncListWidget, UsedListWidget
from custom.graphicsView import GraphicsView
from pyqtconsole.console import PythonConsole
import qss_rc
class MyWin(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.tool_bar = self.addToolBar('工具栏')
        self.action_right_rotate = QtWidgets.QAction(QtGui.QIcon("icons/右旋转.png"), "向右旋转90", self)
        self.action_left_rotate = QtWidgets.QAction(QtGui.QIcon("icons/左旋转.png"), "向左旋转90°", self)
        self.action_histogram = QtWidgets.QAction(QtGui.QIcon("icons/直方图.png"), "直方图", self)
        self.action_right_rotate.triggered.connect(self.right_rotate)
        self.action_left_rotate.triggered.connect(self.left_rotate)
        self.action_histogram.triggered.connect(self.histogram)
        self.tool_bar.addActions((self.action_left_rotate, self.action_right_rotate, self.action_histogram))

        self.useListWidget = UsedListWidget(self)
        self.funcListWidget = FuncListWidget(self)
        self.stackedWidget = StackedWidget(self)
        self.fileSystemTreeView = FileSystemTreeView(self)
        self.graphicsView = GraphicsView(self)
        self.graphicsView.moved.connect(self.show_pos)
        self.dock_file = QtWidgets.QDockWidget(self)
        self.dock_file.setWidget(self.fileSystemTreeView)
        self.dock_file.setTitleBarWidget(QtWidgets.QLabel('目录'))
        self.dock_file.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.dock_func = QtWidgets.QDockWidget(self)
        self.dock_func.setWidget(self.funcListWidget)
        self.dock_func.setTitleBarWidget(QtWidgets.QLabel('图像操作'))
        self.dock_func.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.dock_used = QtWidgets.QDockWidget(self)
        self.dock_used.setWidget(self.useListWidget)
        self.dock_used.setTitleBarWidget(QtWidgets.QLabel('已选操作'))
        self.dock_used.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        self.dock_used.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.dock_attr = QtWidgets.QDockWidget(self)
        self.dock_attr.setWidget(self.stackedWidget)
        self.dock_attr.setTitleBarWidget(QtWidgets.QLabel('属性'))
        self.dock_attr.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)
        self.dock_attr.close()

        self.dock_console = QtWidgets.QDockWidget(self)
        self.console=PythonConsole()
        self.console.push_local_ns('app', QtWidgets.qApp)
        self.console.push_local_ns('mainw', self)
        self.console.push_local_ns('cv2', cv2)
        self.dock_console.setWidget(self.console)
        # self.console.eval_in_thread()
        self.console.eval_queued()
        self.dock_console.setTitleBarWidget(QtWidgets.QLabel('console'))
        self.dock_console.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)

        self.setCentralWidget(self.graphicsView)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_file)
        self.addDockWidget(Qt.TopDockWidgetArea, self.dock_func)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_used)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_attr)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.dock_console)
        self.setWindowTitle('Opencv图像处理')
        self.setWindowIcon(QtGui.QIcon('icons/main.png'))

        self.statusbar = QtWidgets.QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.label=QtWidgets.QLabel(self)
        self.label.setText("hello")
        self.statusbar.addWidget(self.label)
        self.src_img = None
        self.cur_img = None
    def show_pos(self,x,y,val):
        # logging.info("show_pos",x,y)
        self.label.setText(str(x)+","+str(y)+":"+val)
    def update_image(self):
        if self.src_img is None:
            return
        img = self.process_image()
        self.cur_img = img
        self.graphicsView.update_image(img)

    def show_image(self,img):
        self.cur_img = img
        self.graphicsView.change_image(img)
    def show_cnt(self,i):
        app=QtWidgets.qApp
        if(i<len(app.cnts)):
            cnt=app.cnts[i]
            bbox = cv2.boundingRect(cnt)
            (x, y, w, h)=bbox
            img = cv2.rectangle(self.cur_img, (x, y), (x + w, y + h), (255, 0, 0), thickness=1)
            self.show_image(img)
    def change_image(self, img):
        self.src_img = img
        img = self.process_image()
        self.cur_img = img
        self.graphicsView.change_image(img)

    def process_image(self):
        # logging.debug("process_image ============")
        img = self.src_img.copy()
        for i in range(self.useListWidget.count()):
            img = self.useListWidget.item(i)(img)
        return img

    def right_rotate(self):
        self.graphicsView.rotate(90)

    def left_rotate(self):
        self.graphicsView.rotate(-90)

    def histogram(self):
        if len(self.cur_img.shape)==2:
            histr = cv2.calcHist([self.cur_img],[0],None,[256],[0,256])
            histr = histr.flatten()
            plt.plot(range(256), histr, color="gray")
            plt.xlim([0, 256])
            plt.show()
        else:
            color = ('b', 'g', 'r')
            for i, col in enumerate(color):
                histr = cv2.calcHist([self.cur_img], [i], None, [256], [0, 256])
                histr = histr.flatten()
                plt.plot(range(256), histr, color=col)
                plt.xlim([0, 256])
            plt.show()


if __name__ == "__main__":
    from getpath import getpath
    import os
    import logging
    from logging.handlers import RotatingFileHandler
    from PyQt5 import QtWidgets
    handlers=[RotatingFileHandler(filename="cv.log", maxBytes=10*1024*1024,backupCount=3),# logging.FileHandler(initpath+'/myapp.log'),
            logging.StreamHandler(sys.stdout)
    ]
    # handlers=[logging.StreamHandler(sys.stdout)]
    logging.basicConfig(level=logging.DEBUG,
                        format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                        handlers=handlers)
    logging.info('begin')
    app = QtWidgets.QApplication(sys.argv)
    # f=open('./custom/styleSheet.qss', encoding='utf-8')
    # c=f.read()
    # f.close()
    # app.setStyleSheet(c)
    qingyun_style(app)
    window = MyWin()
    app.mainw=window
    window.show()
    sys.exit(app.exec())
